#include "CritSection.h"
//#include "CritSectionQueue.h"
//#include "../comm/ThreadSingletonImp.h"
#include "../include/mystdafx.h"
#include "../os/api.h"


CCritSection::CCritSection( BYTE byLevel, const char* strOwnerName, void* pOwner )
: m_level( byLevel ), m_strOwnerName((char*)strOwnerName), m_pOwner(pOwner)
{
	m_lockTime = 0;

#ifdef _LOCK_DEBUG
	m_nLockCount = 0;
	memset( m_vecLockInfos, 0, sizeof(m_vecLockInfos) );
#endif

	os_mutex_create(&m_mutex);
}

CCritSection::~CCritSection(void)
{
	os_mutex_destroy( &m_mutex );
}

#ifdef _LOCK_DEBUG
void CCritSection::Lock( const char* strFilePath, DWORD dwFileLine )
{
	EnterCritSection();

	if( m_nLockCount < MAX_DEBUG_LEN )
	{
		assert( strlen( strFilePath ) <= OS_MAX_PATH-1 );
		strcpy( m_vecLockInfos[m_nLockCount].strFilePath, strFilePath );
		m_vecLockInfos[m_nLockCount].dwFileLine = dwFileLine;
	}
	m_nLockCount++;
}

void CCritSection::Unlock( const char* strFilePath, DWORD dwFileLine )
{
	if( m_nLockCount <= 0 )
	{
		assert(false);
		return;
	}

	if( m_nLockCount > MAX_DEBUG_LEN )
	{
		--m_nLockCount;
	}
	else
	{
		int nIndex = m_nLockCount-1;
		if( strcpy(m_vecLockInfos[nIndex].strFilePath, strFilePath) == 0 && m_vecLockInfos[nIndex].dwFileLine == dwFileLine )
		{
			m_vecLockInfos[nIndex].strFilePath[0] = '\0';
			m_vecLockInfos[nIndex].dwFileLine = 0;
		}
		else
		{
			//ASSERT(FALSE);
			m_vecLockInfos[nIndex].strFilePath[0] = '\0';
			m_vecLockInfos[nIndex].dwFileLine = 0;
		}
		m_nLockCount--;
	}

	LeaveCritSection();
}

#else
void CCritSection::Lock()
{
	EnterCritSection();
}

void CCritSection::Unlock()
{
	LeaveCritSection();
}
#endif

//////////////////////////////////////////////////////////////////////////

void CCritSection::EnterCritSection()
{

#ifndef _LOCK_DEBUG
	os_mutex_lock( &m_mutex );
#else
	//trdCritSectionQueue->AddLock( this );
	os_mutex_lock( &m_mutex );
	//m_lockTime = os_gettickcount();
#endif
}

void CCritSection::LeaveCritSection()
{
#ifndef _LOCK_DEBUG
	os_mutex_unlock( &m_mutex );
#else
	os_mutex_unlock( &m_mutex );
	//trdCritSectionQueue->RemoveLock( this );
#endif
}

DWORD CCritSection::GetLockSpan()
{
	return os_gettickcount() - m_lockTime;
}














